package jyc_util.copy_on_write_demo;

/**
 * @author haomin
 * @date 2022/05/08 11:10
 **/
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;

public class Main {
    static CopyOnWriteArrayList<String> cow = new CopyOnWriteArrayList<>();

    static class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println(cow.size()); // 只读操作
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(cow.size()); // 只读操作
        }
    }

    public static void main(String[] args) throws InterruptedException {
        cow.add("1");
        cow.add("2");
        cow.add("3");

        MyThread t = new MyThread();
        t.start();

        System.out.println(cow.size()); // 只读操作
        TimeUnit.SECONDS.sleep(1);
        cow.add("4");   // 由于进行了写的操作，所以，会为主线程复制一份元素
        // 导致不是同一份数据了
        System.out.println(cow.size()); // 只读操作
    }
}